package com.eureka.eurekaserviceinvoker.controller;

import com.eureka.eurekaserviceinvoker.interceptor.MyLoadBalancer;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 *
 * 模拟@LoadBalanced注解对RestTemplate处理的负载均衡
 * Created by earl on 2018/4/17.
 */
@Configuration
@RestController
@RequestMapping("/myLoadBalancer")
public class MyLoadBalancerController {


    //使用自定义注解完成负载均衡功能(具体看InterceptorConfig、interceptor的package)
    @MyLoadBalancer
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }




    //测试负载均衡
    @GetMapping("/router")
    public String person( ){
        RestTemplate restTemplate = getRestTemplate();
        //通过服务提供者的应用名称(eureka-service-provider项目的yml设置spring.application.name)调用接口
        String uri = "http://eureka-service-provider/provider/person/2?name=demoTest";
        //由于使用了自定义注解，这里返回的结果会是自定义拦截器替换的URL结果(下面的hello方法)
        return restTemplate.getForObject( uri, String.class);
    }




    /**
     * 测试RestTemplate负载均衡过程（自定义拦截器和注解）
     * @return
     */
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }



}
